package com.example.demo.processor;

import com.example.demo.domain.ContentDO;
import com.example.demo.util.PageGenerator;
import com.example.demo.util.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class ContentProcessor implements Processor {
    @Override
    public ContentDO process(String html) {
        if (StringUtil.isEmpty(html)) {
            return null;
        }
        Document doc = Jsoup.parse(html);
        ContentDO outContentDO = null;
        Optional<Document> document = Optional.of(doc);
        outContentDO = document.map(doc2 -> {
            Element h1 = doc2.selectFirst("h1");
            if (h1 == null) {
                return null;
            }

            Element content = doc2.selectFirst("#content");
            if (content == null) {
                return null;
            }
            String text = content.html();
            text = "<h2 class='text' style=' text-align:center;'>"+h1.text()+"</h2>" + text;
            ContentDO contentDO = new ContentDO();
            String c = text.replaceAll("<script>.*</script>", "");

            Element elementPre = doc2.selectFirst("a.pre");
            Element elementNext = doc2.selectFirst("a.next");
            String generate = PageGenerator.generate(elementPre, elementNext);
            c = c + generate;
            contentDO.setShowContent(c);
            return contentDO;
        }).get();
        return outContentDO;
    }
}
